package gin

import (
	"net/http"
	"strings"
)

type engine struct {
	mrouter *router
	mgroups map[string]*Group
}

func newEngine() *engine {
	e :=  &engine{
		mrouter: newRouter(),
		mgroups: make(map[string]*Group),
	}
	e.mgroups["/"] = e.group("/")
	return e
}

func (g *engine) get(path string,f Handler)  {
	g.mrouter.insert("GET",path,f)
}
func (g *engine) post(path string,f Handler)  {
	g.mrouter.insert("POST",path,f)
}
func (e *engine) group(name string) *Group {
	g := newGroup(e,name)
	e.mgroups[name] = g
	return g
}
func (g *engine) use(f HandlerFunc) {
	g.mgroups["/"].addMid(f)
}


func (e *engine) ServeHTTP(w http.ResponseWriter,req *http.Request) {
//	将w和req封装成ctx
	ctx := newCtx(w,req)
//	向ctx中装载中间件
	for key,val := range e.mgroups {
		if strings.HasPrefix(req.URL.Path,key) {
			ctx.addMid(val.midllers...)
		}
	}
//	通过路由对ctx进行处理
	e.mrouter.serve(ctx)
}
